import type {
  IRegisterForm,
} from '@/api/login'
import { defineStore } from 'pinia'
import {
  register as _register,
  wxLogin as _wxLogin,
  getWxCode,
} from '@/api/login'

export const useTokenStore = defineStore(
  'token',
  () => {
    const token = ref('')

    async function wxLogin() {
      try {
        const code = await getWxCode()
        const tokenInfo = await _wxLogin({ code: code.code })
        token.value = tokenInfo
        return tokenInfo
      }
      catch (error) {
        if (error.code === 404) {
          uni.redirectTo({ url: '/pages/login/index' })
        }
        return Promise.reject(error)
      }
    }

    async function register(data: Omit<IRegisterForm, 'code'>) {
      const code = await getWxCode()
      const tokenInfo = await _register({ ...data, code: code.code })
      token.value = tokenInfo
    }

    return {
      wxLogin,
      register,
      token,
    }
  },
  {
    // 添加持久化配置，确保刷新页面后token信息不丢失
    persist: true,
  },
)
